package admin

import (
	"github.com/labstack/echo/v4"
	"strconv"

	"night-school-api/models"
	"night-school-api/utils"
	"night-school-api/database"
)

func GetComments(c echo.Context) error {
	adminUid := c.Get("uid").(int)
	if adminUid <= 0 {
		return utils.JSONError(c, "未登录")
	}

	db := database.DB
	query := db.Model(&models.Admin{})
	var admin models.Admin

	query.Find(&admin, adminUid)
	adminCountyIndex := admin.CountyIndex

	courseID, err := strconv.Atoi(c.QueryParam("course_id"))
	if err != nil {
		courseID = 0
	}

	query = db.Model(&models.CommentWithUser{})
	if (courseID > 0) {
		query = query.Where("course_id = ?", courseID)
	} else {
		if adminCountyIndex > 0 {
			query = query.InnerJoins("inner join courses on comments.course_id = courses.id").Where("courses.county_index = ?", adminCountyIndex)
		}
	}


	order := "id DESC"

	var total int64
	var comments []models.CommentWithUser
	query.Count(&total)
	page, size := utils.GetPagination(c)
	query.Order(order).Preload("User").Limit(size).Offset((page - 1) * size).Find(&comments)

	// 修改评论状态为：已处理
	var idList []int
	for _, comment := range comments {
		idList = append(idList, comment.ID)
	}
	if len(idList) > 0 {
		db.Model(&models.Comment{}).Where("id IN ?", idList).Update("status", 1)
	}
	
	return utils.JSONPagination(c, page, size, total, comments)
}